package ThreadDemo1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 故我
 * Date: 2023-10-12
 * Time: 18:05
 */
class MyBlockingQueue {
    public int[] items = new int[1000];
    public int head = 0;
    public int tail = 0;
    public int size = 0;

    public void put(int value) throws InterruptedException {
        synchronized (this) {
            while (size == items.length) {
                this.wait();//阻塞等待
            }
            items[tail] = value;
            tail++;
            //环形队列的结构
            if (tail >= items.length) {
                tail = 0;
            }
            size++;
            this.notify();//生产一个，唤醒线程
        }
    }

    public int take() throws InterruptedException {
        int result = 0;
        synchronized (this) {
            while (size == 0) {
                this.wait();//当队列中没有元素时
            }
            result = items[head];
            head++;
            if (head >= items.length) {
                head = 0;
            }
            size--;
            this.notify();
        }
        return result;
    }
}

public class ThreadDemo22 {
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue();

        Thread customer = new Thread(() -> {
            while (true) {
                try {
                    int res = myBlockingQueue.take();
                    System.out.println("消费者消费: " + res);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        customer.start();

        Thread produtor = new Thread(() -> {
            int count = 0;
            while (true) {
                count++;
                try {
                    System.out.println("生产者生产: " + count);
                    myBlockingQueue.put(count);

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        produtor.start();
    }
}
